/**
 * UpdateTale
 * 
 * 10/10/2013
 * 
 * Copyright GPL
 */
package info.victor.servlets;

import info.victor.utils.AccessDB;
import info.victor.utils.StringUtils;
import info.victor.utils.WebUtils;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class UpdateTale
 * This servlet is for updating the tale
 */
@WebServlet("/Update")
public class Update extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
    /**
     * Constructor
     * @see HttpServlet#HttpServlet()
     */
    public Update() {
        super();
    }

	/**
	 * this method opens the update.jsp passing a Tale with parameters
	 * for showing the title and the tale there.
	 * @see HttpServlet#doGet(HttpServletRequest request, 
	 * HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, 
					IOException {
		
		String id = request.getParameter("id");
		
		if(StringUtils.isNumber(id)){
			request.setAttribute("tale", new AccessDB().getTale(id));
			WebUtils.redirect(this, request, "/update.jsp", response);
		}else{
			WebUtils.redirect(this, request, "/Home", response);
		}
	}
	
	/**
	 * This method updates a tale
	 * @see HttpServlet#doPost(HttpServletRequest request, 
	 * HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, 
					IOException {
		
		String id = request.getParameter("id");
		String title = request.getParameter("title");
		String tale = request.getParameter("tale");
		
		if(StringUtils.checkVoidStrings(title, tale)){
			new AccessDB().updateTale(id, title, tale);
			WebUtils.redirect(this, request, "/Home", response);
		}
	}

}
